import React, { useState, useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { Container } from '@/components/common/container';
import { Toolbar, ToolbarActions, ToolbarHeading } from '@/layouts/demo1/components/toolbar';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { Badge } from '@/components/ui/badge';
import { Plus, Upload, X, ArrowLeft } from 'lucide-react';

const ProductFormPage = () => {
  const navigate = useNavigate();
  const { id } = useParams();
  const [formData, setFormData] = useState({
    name: '',
    category: '',
    price: '',
    stock: '',
    description: '',
    tags: []
  });
  const [newTag, setNewTag] = useState('');

  // 模拟获取商品数据（编辑模式）
  useEffect(() => {
    if (id) {
      // 这里应该调用API获取商品详情
      // 暂时使用模拟数据
      setFormData({
        name: 'Apple iPhone 15 Pro',
        category: 'phone',
        price: '8999',
        stock: '50',
        description: '最新一代旗舰手机，搭载A17芯片，超强影像系统。',
        tags: ['热销', '新品']
      });
    }
  }, [id]);

  const handleSave = () => {
    // 这里应该调用API保存商品
    console.log('保存商品:', formData);
    navigate('/product-management/product-list');
  };

  const handleCancel = () => {
    navigate('/product-management/product-list');
  };

  const handleAddTag = () => {
    if (newTag.trim() && !formData.tags.includes(newTag.trim())) {
      setFormData(prev => ({
        ...prev,
        tags: [...prev.tags, newTag.trim()]
      }));
      setNewTag('');
    }
  };

  const handleRemoveTag = (tagToRemove) => {
    setFormData(prev => ({
      ...prev,
      tags: prev.tags.filter(tag => tag !== tagToRemove)
    }));
  };

  const handleFieldChange = (field, value) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  return (
    <>
      <Container>
        <Toolbar>
          <ToolbarHeading
            title={id ? '编辑商品' : '添加商品'}
            description={id ? '修改商品信息' : '创建新的商品信息'}
          />
          <ToolbarActions>
            <Button variant="outline" onClick={handleCancel}>
              <ArrowLeft className="size-4 me-2" />
              返回
            </Button>
            <Button onClick={handleSave}>
              {id ? '更新商品' : '保存商品'}
            </Button>
          </ToolbarActions>
        </Toolbar>
      </Container>
      
      <Container>
        <Card>
          <CardHeader>
            <CardTitle>商品信息</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-6">
              {/* 基本信息 */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="space-y-2">
                  <Label htmlFor="name">商品名称 *</Label>
                  <Input 
                    id="name" 
                    value={formData.name}
                    onChange={(e) => handleFieldChange('name', e.target.value)}
                    placeholder="请输入商品名称" 
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="category">商品分类 *</Label>
                  <Select value={formData.category} onValueChange={(value) => handleFieldChange('category', value)}>
                    <SelectTrigger>
                      <SelectValue placeholder="请选择商品分类" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="phone">手机</SelectItem>
                      <SelectItem value="laptop">笔记本</SelectItem>
                      <SelectItem value="tablet">平板</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="price">商品价格 *</Label>
                  <Input 
                    id="price" 
                    type="number" 
                    value={formData.price}
                    onChange={(e) => handleFieldChange('price', e.target.value)}
                    placeholder="请输入商品价格" 
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="stock">库存 *</Label>
                  <Input 
                    id="stock" 
                    type="number" 
                    value={formData.stock}
                    onChange={(e) => handleFieldChange('stock', e.target.value)}
                    placeholder="请输入库存数量" 
                  />
                </div>
              </div>

              {/* 商品描述 */}
              <div className="space-y-2">
                <Label htmlFor="description">商品描述</Label>
                <Textarea 
                  id="description" 
                  value={formData.description}
                  onChange={(e) => handleFieldChange('description', e.target.value)}
                  placeholder="请输入商品描述" 
                  rows={4} 
                />
              </div>

                            {/* 商品标签 */}
              <div className="space-y-2">
                <Label>商品标签</Label>
                <div className="flex gap-2">
                  <Input 
                    value={newTag}
                    onChange={(e) => setNewTag(e.target.value)}
                    placeholder="输入标签后按回车添加"
                    onKeyPress={(e) => {
                      if (e.key === 'Enter') {
                        e.preventDefault();
                        handleAddTag();
                      }
                    }}
                  />
                  <Button type="button" variant="outline" onClick={handleAddTag}>
                    <Plus className="size-4" />
                  </Button>
                </div>
                {formData.tags.length > 0 && (
                  <div className="flex flex-wrap gap-2 mt-2">
                    {formData.tags.map((tag, index) => (
                      <Badge key={index} variant="secondary" className="gap-1">
                        {tag}
                        <button 
                          className="ml-1 hover:text-destructive"
                          onClick={() => handleRemoveTag(tag)}
                        >
                          <X className="size-3" />
                        </button>
                      </Badge>
                    ))}
                  </div>
                )}
              </div>

              {/* 商品图片 */}
              <div className="space-y-2">
                <Label>商品图片</Label>
                <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                  <label className="border-2 border-dashed border-muted-foreground/25 rounded flex items-center justify-center h-24 cursor-pointer hover:border-muted-foreground/50 transition-colors">
                    <div className="text-center">
                      <Upload className="size-6 mx-auto mb-1 text-muted-foreground" />
                      <span className="text-xs text-muted-foreground">上传图片</span>
                    </div>
                    <input type="file" accept="image/*" multiple className="hidden" />
                  </label>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      </Container>
    </>
  );
};

export default ProductFormPage; 